//
//  SelectStep1ViewController.m
//  OutesIOS
//
//  Created by norman on 2019/1/6.
//  Copyright © 2019 norman. All rights reserved.
//

#import "SelectStep1ViewController.h"
#import "EditorTableViewCell.h"
#import "TerminalTypeTableViewCell.h"
#import "JFCityViewController.h"
#import "CustomIOSAlertView.h"
#import "BigMachine_TabViewController.h"
#import "BottomActionView.h"
#import "HeatProjectData.h"
#import "SelectStep2ViewController.h"


@interface SelectStep1ViewController ()<JFCityViewControllerDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;

@end

@implementation SelectStep1ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"项目基本信息";
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self setupBaseViews];
}

- (void)dealloc {
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}


#pragma mark - 初始化视图
- (void)setupBaseViews {
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    @weakObj(self);
    [self.footerView addRightBtnBlock:^(id obj) {
        if (![Weakself validProjectData]) {
            return;
        }
        [Weakself modifyProject:^(BOOL result) {
            if (result) {
                SelectStep2ViewController *vc = [SelectStep2ViewController new];
                [Weakself.navigationController pushViewController:vc animated:YES];
            } else {
                [Tools showMessageCenter:@"保存数据失败！"];
            }
        }];
    }];
    [self.footerView setLeftBtnTitle:@"" andRightBtnTitle:@"下一步" andCenterTitle:@"1/3"];
    [self.view addSubview:self.footerView];
}


- (void)setupViews{
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    [self.tableView registerClass:[EditorTableViewCell class] forCellReuseIdentifier:@"edit"];
    [self.tableView registerClass:[TerminalTypeTableViewCell class] forCellReuseIdentifier:@"ter"];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

/**
 *  直接跳转到项目页面
 */
-(void) onBackToProject{
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[BigMachine_TabViewController class]]) {
            [(BigMachine_TabViewController*)tmp loadData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 加载数据
/**
 *  初始化数据
 */
- (void)initData {
    //初始化上一步下一步信息中的步数
    kHeatProject = nil;
    if ([Tools isEmpty:self.heat_project_id]) {
        [[ProjectManager manager]initStepInfo:YES];
    } else {
        [[ProjectManager manager]initStepInfo:NO];
    }
    
}

- (void)loadData {
    if (![Tools isEmpty:self.heat_project_id]) {
        //修改项目
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        [param setValue:self.heat_project_id forKey:@"heat_project_id"];
        
        [HttpClient getWithUrl:HTTP_GET_HEAT_PROJECT_INFO token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            kHeatProject = obj;
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            [self.tableView.mj_header endRefreshing];
        }];
    } else {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        NSDictionary *city = [Tools getApplicationData:CityName];
        if (city != nil) {
            NSString *name = [city objectForKey:@"city"];
            NSString *guid = [city objectForKey:@"id"];
            if (![Tools isEmpty:name]) {
                [param setValue:name forKey:@"city_name"];
            }
            if (![Tools isEmpty:guid]) {
               [param setValue:guid forKey:@"city_id"];
            }
        }
        [HttpClient postWithUrl:HTTP_POST_HEAT_PROJECT_NEW token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            self.heat_project_id = obj.heat_project_id;
            kHeatProject = obj;
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            [self.tableView.mj_header endRefreshing];
        }];
    }
}

- (BOOL)validProjectData {
    if ([Tools isEmpty:kHeatProject.heat_project_name]) {
        [Tools showMessageCenter:@"项目名称不能为空！"];
        return NO;
    }
    if (kHeatProject.heat_days <= 0) {
        [Tools showMessageCenter:@"供暖天数必须大于0！"];
        return NO;
    }
    return YES;
}

- (void)modifyProject:(void (^)(BOOL))result{
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kHeatProject.heat_project_id forKey:@"heat_project_id"];
    [params setValue:kHeatProject.heat_project_name forKey:@"heat_project_name"];
    [params setValue:kHeatProject.city_id forKey:@"city_id"];
    [params setValue:kHeatProject.city_name forKey:@"city_name"];
    [params setValue:@(kHeatProject.heat_days) forKey:@"heat_days"];
    [params setValue:@(kHeatProject.calc_t) forKey:@"calc_t"];
    [params setValue:@(kHeatProject.extreme_t) forKey:@"extreme_t"];
    [params setValue:@(kHeatProject.e_price) forKey:@"e_price"];
    [params setValue:@(kHeatProject.w_price) forKey:@"w_price"];
    [params setValue:@(kHeatProject.a_price) forKey:@"a_price"];
    [params setValue:@(kHeatProject.c_price) forKey:@"c_price"];
    [params setValue:@(kHeatProject.o_price) forKey:@"o_price"];
    [params setValue:@(kHeatProject.b_price) forKey:@"b_price"];
    [params setValue:@(kHeatProject.s_price) forKey:@"s_price"];
    [params setValue:@(kHeatProject.h_price) forKey:@"h_price"];
    
//    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    [HttpClient postWithUrl:HTTP_POST_HEAT_PROJECT_UPDATE token:[AccountManager manager].token paramDic:params resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
//        [MBProgressHUD hideHUDForView:self.view];
        result(YES);
    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUDForView:self.view];
        result(NO);
    }];
    
}

/**
 *  检查项目信息输入是否合理
 *
 *  @return 是否通过了验证
 */
- (BOOL)checkHeatProjectInfo {
    if ([Tools isEmpty:kHeatProject.city_name]) {
        [Tools showMessageCenter:@"项目地点不能为空！"];
        return NO;
    }
    if ([Tools isEmpty:kHeatProject.heat_project_name]) {
        [Tools showMessageCenter:@"项目名称不能为空！"];
        return NO;
    }
    if (kHeatProject.heat_days <= 0) {
        [Tools showMessageCenter:@"供暖天数必须大于0！"];
        return NO;
    }
    
    return YES;
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }
    return 8;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"edit"];
    if (indexPath.section == 0) {
        UITableViewCell *Selectcell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"SelectArea_Cell"];
        Selectcell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
        Selectcell.detailTextLabel.textColor = CM_TABLE_INFO_COLOR;
        if (indexPath.row == 0) {
            [cell setKeyboardType:UIKeyboardTypeDefault];
            if (![Tools isEmpty:kHeatProject.heat_project_name]) {
                [cell setTitleStr:@"项目名称" andColor:nil andHintStr:@"XX工程XXX项目" andInputViewIsHidden:NO andInfoStr:kHeatProject.heat_project_name andUnit:nil];
                [cell setEditorText:kHeatProject.heat_project_name];
            }
            else {
                [cell setTitleStr:@"项目名称" andColor:nil andHintStr:@"XX工程XXX项目" andInputViewIsHidden:NO andInfoStr:nil andUnit:nil];
            }
            //            [cell.editorView becomeFirstResponder];
            cell.TextFiledValueBlock = ^(NSString *value) {
                kHeatProject.heat_project_name = value;
            };
//            [cell setItemIsNesessory];
        } else if (indexPath.row == 1) {
            Selectcell.textLabel.text = @"所在城市";
            if (kHeatProject == nil || [Tools isEmpty:kHeatProject.city_name]) {
                Selectcell.detailTextLabel.text = @"请选择";
            } else {
                Selectcell.detailTextLabel.text = kHeatProject.city_name;
            }
            Selectcell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return Selectcell;
        } else if (indexPath.row == 2) {
            [cell setTitleStr:@"供暖天数" andColor:nil andHintStr:@"请输入供暖天数" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"天"];
            if (kHeatProject.heat_days != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%d", kHeatProject.heat_days]];
            }
            [cell setKeyboardType:UIKeyboardTypeNumberPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value intValue] >= 0) {
                    kHeatProject.heat_days = [value intValue];
                }
            };
        } else if (indexPath.row == 3) {
            [cell setTitleStr:@"采暖计算温度" andColor:nil andHintStr:@"请输入采暖计算温度" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"℃"];
            if (kHeatProject.calc_t != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.1f", kHeatProject.calc_t]];
            }
            [cell setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
            cell.TextFiledValueBlock = ^(NSString *value){
                kHeatProject.calc_t = [value doubleValue];
            };
        } else {
            [cell setTitleStr:@"采暖极端温度" andColor:nil andHintStr:@"请输入采暖极端温度" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"℃"];
            if (kHeatProject.extreme_t != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.1f", kHeatProject.extreme_t]];
            }
            [cell setKeyboardType:UIKeyboardTypeNumbersAndPunctuation];
            cell.TextFiledValueBlock = ^(NSString *value){
                kHeatProject.extreme_t = [value doubleValue];
            };
        }
        return cell;
    } else {
        if (indexPath.row == 0) {
            [cell setTitleStr:@"电价" andColor:nil andHintStr:@"请输入电价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/度"];
            if (kHeatProject.e_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.1f", kHeatProject.e_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.e_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 1) {
            [cell setTitleStr:@"水价" andColor:nil andHintStr:@"请输入水价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/m³"];
            if (kHeatProject.w_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.w_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.w_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 2) {
            [cell setTitleStr:@"天然气价" andColor:nil andHintStr:@"请输入天然气价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/m³"];
            if (kHeatProject.a_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.a_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.a_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 3) {
            [cell setTitleStr:@"煤价" andColor:nil andHintStr:@"请输入煤价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/kg"];
            if (kHeatProject.c_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.c_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.c_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 4) {
            [cell setTitleStr:@"重油价" andColor:nil andHintStr:@"请输入重油价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/kg"];
            if (kHeatProject.o_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.o_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.o_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 5) {
            [cell setTitleStr:@"生物质价" andColor:nil andHintStr:@"请输入生物质价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/kg"];
            if (kHeatProject.b_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.b_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.b_price = [value doubleValue];
                }
            };
        } else if (indexPath.row == 6) {
            [cell setTitleStr:@"蒸汽价" andColor:nil andHintStr:@"请输入蒸汽价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/m³"];
            if (kHeatProject.s_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.s_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.s_price = [value doubleValue];
                }
            };
        } else {
            [cell setTitleStr:@"市政供暖价" andColor:nil andHintStr:@"请输入市政供暖价" andInputViewIsHidden:NO andInfoStr:nil andUnit:@"元/㎡"];
            if (kHeatProject.h_price != 0) {
                [cell setEditorText:[NSString stringWithFormat:@"%.2f", kHeatProject.h_price]];
            } else {
                [cell setEditorText:@""];
            }
            [cell setKeyboardType:UIKeyboardTypeDecimalPad];
            cell.TextFiledValueBlock = ^(NSString *value){
                if ([value doubleValue] >= 0) {
                    kHeatProject.h_price = [value doubleValue];
                }
            };
        }
    }
    return cell;
}

- (void)cityName:(NSString *)name {
    kHeatProject.city_name = name;
    [[DBManager manager]open:DB_Weather];
    kHeatProject.city_id = [[DBManager manager]queryStringData:[NSString stringWithFormat:@"select Id from Cities WHERE Name = '%@'",name]];
    NSMutableDictionary *city = [NSMutableDictionary new];
    [city setObject:name forKey:@"city"];
    [city setObject:kHeatProject.city_id forKey:@"id"];
    [Tools saveApplicationData:city forKey:CityName];
    //获取城市相关数据
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:kHeatProject.city_id forKey:@"city_id"];
    [MBProgressHUD showMessage:@"数据查询中..." toView:self.view];
    [HttpClient getWithUrl:HTTP_GET_HEAT_PROJECT_CITY_DATA token:[[AccountManager manager]token] paramDic:param resultClass:[HeatProjectData class] success:^(HeatProjectData *obj) {
        kHeatProject.calc_t = obj.calc_t;
        kHeatProject.extreme_t = obj.extreme_t;
        kHeatProject.heat_days = obj.heat_days;
        [MBProgressHUD hideHUDForView:self.view];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForItem:1 inSection:0], [NSIndexPath indexPathForItem:2 inSection:0], [NSIndexPath indexPathForItem:3 inSection:0], [NSIndexPath indexPathForItem:4 inSection:0], nil] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            //选择地点
            JFCityViewController *cityViewController = [[JFCityViewController alloc] init];
            //  设置代理
            cityViewController.delegate = self;
            cityViewController.title = @"城市";
            //  给JFCityViewController添加一个导航控制器
            UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:cityViewController];
            [navigationController.navigationBar setTintColor:[UIColor whiteColor]];
            [self presentViewController:navigationController animated:YES completion:nil];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ProjectStep1Cell";
    EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return [cell getHeight];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, DEFAULT_SECTION_HEIGHT)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return DEFAULT_SECTION_HEIGHT;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
